var express = require('express');
var logger = require('morgan');
var app = express();
var mongoose = require('mongoose');
var KLPS = require('./index.js');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var RedisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var path = require('path');



var config = {
    "cookie": {
        "maxAge": 1800000
    },
    "sessionStore": {
        "name": "klps",
        "host": "localhost",
        "port": "6379",
        "ttl": 30,
        "logErrors": true
    }
}



app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));



app.use(cookieParser());
// 此时req对象还没有session这个属性
app.use(session({
    cookie: config.cookie,
    store: new RedisStore(config.sessionStore),
    secret: 'express is powerful'
}));
// 经过中间件处理后，可以通过req.session访问session object。比如如果你在session中保存了session.userId就可以根据userId查找用户的信息了。



var klps = new KLPS(app);
// 连接数据库
var uri = 'mongodb://127.0.0.1/klps';
mongoose.connect(uri, {
    useMongoClient: true
}, function(err) {
    if (!err) {
        console.log('connect db success')
    }
});
mongoose.connection.on('error', console.error.bind(console, '连接错误:'));
app.set('views', path.resolve(__dirname, './views/'))
app.set("view engine", "ejs");





app.get('/', klps.authentication, function(req, res, next) {
    res.render('home', { user: req.session.user })
});
app.get('/login', function(req, res, next) {
    res.render('login')
});
app.post('/doLogin', klps.login, function(req, res, next) {
    res.render('home', { user: req.session.user })
})

app.get('/logout', klps.logout, function(req, res, next) {
    res.render('login')
})
app.get('/register', function(req, res, next) {
    res.render('register')
})
app.post('/doRegister', klps.register, function(req, res, next) {
    res.status(200).send("success")
})
module.exports = app;
app.listen(8000);